在 .NET Framework 裡,有關 Web.config (App.config) 的應用
TLDR
- 使用組建組態 (Build Configuration) 配合 Web.config Transform,可自動化產出對應環境的設定檔,避免手動修改錯誤。
- 非 Web 專案預設不支援 Config Transform,需安裝
SlowCheetah擴充套件或 NuGet 套件。 - 透過
configSource或file屬性,可將共用設定(如連線字串)抽離至獨立檔案,供多個專案引用。 - 透過
<location inheritInChildApplications="false">可切斷子網站對父網站 Web.config 的繼承,避免設定衝突。 - Entity Framework Database First 模式下,連線字串不建議使用外部引用或
<location>標籤,否則會導致設計階段 UI 無法讀取設定。
依不同組建組態發佈不同的設定檔
在開發、測試與正式環境中,設定檔內容往往不同。透過組建組態(Debug/Release)結合 Web.config Transform 機制,可以在發佈時自動轉換設定值。
Web 專案的 Web.config Transform
當專案中缺少對應組態的 Web.{組態名稱}.config 時,可於 Web.config 點擊右鍵選擇「新增設定轉換」。
- 替換機制:使用
xdt:Transform定義行為,xdt:Locator定義目標。 - 常用轉換範例:xml
<!-- 替換整個節點 --> <connectionStrings xdt:Transform="Replace"> <add name="Default" connectionString="..." /> </connectionStrings> <!-- 根據屬性匹配並替換單一屬性 --> <add key="MyKey" value="NewValue" xdt:Locator="Match(key)" xdt:Transform="SetAttributes" /> <!-- 移除屬性 --> <compilation xdt:Transform="RemoveAttributes(debug)" />
非 Web 專案的 App.config Transform
非 Web 專案原生不支援此功能,需透過以下方式處理:
- 安裝套件:安裝 Visual Studio 延伸模組「SlowCheetah」或 NuGet 套件
Microsoft.VisualStudio.SlowCheetah。 - 建置行為:非 Web 專案發佈時,建置過程會觸發 Transform。建議在建置前先清理
bin資料夾以確保產出正確。
TIP
建立發佈設定檔時產生的 {Profile}.pubxml.user 檔案為使用者設定紀錄,不應納入版控。
不同專案共用設定檔
當多個專案(如 Web API、排程程式)共用同一資料庫設定時,可將設定抽離至獨立檔案。
設定步驟
- 建立外部設定檔:建立如
Connection.config等檔案,並設定xdt:Transform。 - 專案引用:以「連結方式」加入檔案,並在
.csproj檔中設定:- 設定
<TransformOnBuild>true</TransformOnBuild>。 - 外部設定檔設定
<CopyToOutputDirectory>Always</CopyToOutputDirectory>。 - 外部組態設定檔設定
<None />節點,避免發佈時被複製。
- 設定
- 引用方式:
configSource:適用於connectionStrings或smtp,不允許合併其他設定。file:適用於appSettings,允許合併其他設定。
WARNING
若使用 Entity Framework Database First,請勿將連線字串移至外部引用檔,否則 Entity Framework 的設計介面將無法讀取連線字串。
切斷 Web.config 的繼承關係
當 IIS 子網站發生設定衝突(例如 Framework 版本不同)時,可在父網站的 Web.config 中使用 <location> 標籤切斷繼承:
xml
<location path="." inheritInChildApplications="false">
<system.web>
<!-- 內部設定 -->
</system.web>
</location>TIP
切勿將 <location> 標籤包覆在 Entity Framework 的連線字串外層,否則會導致 EF 設計介面讀取失敗。
異動歷程
- 2022-11-10 初版文件建立。
